<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class WxUserInfo extends Model
{
    const APPID='wxc8e46fa6249b55ef';
    const APPSECRET='475d9adf6b74595f3c69dd542cd05ca5';
    //绑定数据表
    protected $table="wx_userinfo";
    //curl请求
    public function getRequest($url, $refer = "", $timeout = 10)
    {
        $ssl = stripos($url,'https://') === 0 ? true : false;
        $curlObj = curl_init();
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_AUTOREFERER => 1,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
            CURLOPT_HTTPHEADER => ['Expect:'],
            CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
        ];
        if ($refer) {
            $options[CURLOPT_REFERER] = $refer;
        }
        if ($ssl) {
            //support https
            $options[CURLOPT_SSL_VERIFYHOST] = false;
            $options[CURLOPT_SSL_VERIFYPEER] = false;
        }
        curl_setopt_array($curlObj, $options);
        $returnData = curl_exec($curlObj);
        if (curl_errno($curlObj)) {
            //error message
            $returnData = curl_error($curlObj);
        }
        curl_close($curlObj);
        return $returnData;
    }
    //code换取openid
    public function getOpenid($code){
        $url='https://api.weixin.qq.com/sns/jscode2session?appid='.self::APPID.'&secret='.self::APPSECRET.'&js_code='.$code.'&grant_type=authorization_code';
        return $this->getRequest($url);
    }
    //入库
    public function insertData($openid,$nickname,$img){
        $this->openid=$openid;
        $this->nickname=$nickname;
        $this->img=$img;
        return $this->save();
    }
    //防止重复入库
    public function uniqueAddData($openid){
        return $this->where('openid',$openid)->count();
    }
    //添加积分
    public function addScore($openid){
        return $this->where('openid',$openid)->increment('score',10);
    }
    //添加日志
    public function file_logs($openid,$nickname,$action){
         $content='用户为'.$nickname.'的用户在'.date('Y-m-d H:i:s',time()).'进行了'.$action.'操作';
         $file_name=$openid.'.txt';
         $path=public_path('/file_login_log/'.$file_name);
         file_put_contents($content,$path,8);
    }
}
